package com.ruoyi.web.controller.system;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.websocket.server.PathParam;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.enums.BusinessStatus;
import com.ruoyi.common.page.TableDataInfo;
import com.ruoyi.common.utils.Constans;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.system.domain.HatchetAgent;
import com.ruoyi.system.domain.HatchetIssBank;
import com.ruoyi.system.domain.HatchetMerchant;
import com.ruoyi.system.domain.HatchetMoneyChange;
import com.ruoyi.system.domain.HatchetOrderPayment;
import com.ruoyi.system.service.IHatchetAgentService;
import com.ruoyi.system.service.IHatchetIssBankService;
import com.ruoyi.system.service.IHatchetMerchantService;
import com.ruoyi.system.service.IHatchetMoneyChangeService;
import com.ruoyi.system.service.IHatchetOrderPaymentService;

import net.sf.json.JSONObject;

/**
 * 商户列 信息操作处理
 * 
 * @author ruoyi
 * @date 2019-02-18
 */
@Controller
@RequestMapping("/system/hatchetMerchant")
public class HatchetMerchantController extends BaseController {
	private String prefix = "system/hatchetMerchant";

	@Autowired
	private IHatchetMerchantService hatchetMerchantService;
	@Autowired
	private IHatchetAgentService agentService;
	@Autowired
	private IHatchetIssBankService issBankService;
	@Autowired
	private IHatchetOrderPaymentService  orderPaymentService;
	@Autowired
	private IHatchetMoneyChangeService  moneyChangeService;
	@RequiresPermissions("system:hatchetMerchant:view")
	@GetMapping()
	public String hatchetMerchant(ModelMap mmap) {
		HatchetMerchant hatchetMerchant = new HatchetMerchant();
		hatchetMerchant.setAgentId(null);
		mmap.put("hatchetMerchant", hatchetMerchant);
		return prefix + "/hatchetMerchant";
	}

	// 查询是代理商的商户
	@RequiresPermissions("system:hatchetMerchant:view")
	@GetMapping("/{agentId}")
	public String hatchetMerchant(@PathVariable("agentId") String agentId, ModelMap mmap) {
		// 把id返回去
		HatchetMerchant hatchetMerchant = new HatchetMerchant();
		hatchetMerchant.setAgentId(agentId);
		mmap.put("hatchetMerchant", hatchetMerchant);
		return prefix + "/hatchetMerchant";
	}

	// 查询经理人
	@RequiresPermissions("system:hatchetMerchant:view")
	@GetMapping("/jlr")
	public String selectJLR(ModelMap mmap) {
		HatchetMerchant hatchetMerchant = new HatchetMerchant();
		hatchetMerchant.setAgentId(null);
		mmap.put("hatchetMerchant", hatchetMerchant);
		return prefix + "/hatchetMerchantJLR";
	}
	
	/**
	 * 查询商户列列表
	 */
	@RequiresPermissions("system:hatchetMerchant:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(HatchetMerchant hatchetMerchant)
	{
		HatchetAgent agent = new HatchetAgent();
		if (hatchetMerchant.getAgentNo() != null) {
			agent.setAgentNo(hatchetMerchant.getAgentNo());
		} else {
			agent.setAgentNo("");
		}
		if (hatchetMerchant.getAgentName() != null) {
			agent.setAgentName(hatchetMerchant.getAgentName());
		} 
		List<HatchetAgent> agentList = agentService.selectHatchetAgentByaction(agent);
		if (agentList.size() > 0) {
			hatchetMerchant.setAgentId(agentList.get(0).getID());
		}
		//设置level查询条件
		if(StringUtils.isNotEmpty(hatchetMerchant.getLEVEL())) {
			hatchetMerchant.setLEVEL("0"+hatchetMerchant.getLEVEL());
		}
		startPage();
		List<HatchetMerchant> list = hatchetMerchantService.selectHatchetMerchantList(hatchetMerchant);
		
		for (HatchetMerchant hatchetMerchant2 : list) {
			if (hatchetMerchant2.getAgentId() != null) {
				HatchetAgent hatchetAgent = agentService.selectHatchetAgentById(hatchetMerchant2.getAgentId());
				if (hatchetAgent != null) {
					hatchetMerchant2.setAgentName(hatchetAgent.getAgentName());
					hatchetMerchant2.setAgentNo(hatchetAgent.getAgentNo());
				}
			}
			//当用户等级为2  判断用户的升级经纪人时间是否为空  如果不为空就是“经理”对应level=4 为空就是“经理（未激活）”对应level=2
			if("2".equals(hatchetMerchant2.getLEVEL())) {
				if(StringUtils.isNotNull(hatchetMerchant2.getSubmitReexamineTime())) {
					hatchetMerchant2.setLEVEL("4");//新升级的经理
				}
			}
			if (StringUtils.isNotEmpty(hatchetMerchant2.getBankCode())) {
				// 匹配银行名称
				HatchetIssBank issBankByBank = issBankService
						.selectHatchetIssBankByBankCode(hatchetMerchant2.getBankCode());
				if (StringUtils.isNotNull(issBankByBank)) {
					hatchetMerchant2.setBankName(issBankByBank.getBankName());
				}
			}
			if (hatchetMerchant2.getParentPhone() != null) {
				HatchetMerchant newMerchant = new HatchetMerchant();
				newMerchant.setPHONE(hatchetMerchant2.getParentPhone());
				List<HatchetMerchant> merlist = hatchetMerchantService.selectHatchetMerchantList(newMerchant);
				if (merlist.size() > 0) {
					hatchetMerchant2.setParentName(merlist.get(0).getMerchantCnName());
				}
			}
			//查询用户活跃度 查询用户的最近的一次的订单
			HatchetOrderPayment orderPayment = new HatchetOrderPayment();
			orderPayment.setMerchantId(hatchetMerchant2.getID());
			orderPayment.setSTATUS("10B");
			List<HatchetOrderPayment> orderPaymentList = orderPaymentService.selectHatchetOrderPaymentList(orderPayment);
			if (StringUtils.isNotEmpty(orderPaymentList)) {
				Date completeTime = orderPaymentList.get(0).getCompleteTime();
				if (StringUtils.isNotNull(completeTime)) {
					String liveness = DateUtils.formetaDiff(completeTime);
					hatchetMerchant2.setLiveness(liveness);
				}
				
			}else {
				hatchetMerchant2.setLiveness("不活跃");
			}
			//查询用户消费总金额
			BigDecimal selectSumMoney = orderPaymentService.selectSumMoney(orderPayment);
			hatchetMerchant2.setCreditRate(selectSumMoney);
		}
		return getDataTable(list);
	}

	/**
	 * 导出商户列列表
	 */
	@RequiresPermissions("system:hatchetMerchant:export")
	@PostMapping("/export")
	@ResponseBody
	public AjaxResult export(HatchetMerchant hatchetMerchant) {
		HatchetAgent agent = new HatchetAgent();
		if (hatchetMerchant.getAgentNo() != null) {
			agent.setAgentNo(hatchetMerchant.getAgentNo());
		} else {
			agent.setAgentNo("");
		}
		if (hatchetMerchant.getAgentName() != null) {
			agent.setAgentName(hatchetMerchant.getAgentName());
		} 
		List<HatchetAgent> agentList = agentService.selectHatchetAgentByaction(agent);
		if (agentList.size() > 0) {
			hatchetMerchant.setAgentId(agentList.get(0).getID());
		}
		List<HatchetMerchant> list = hatchetMerchantService.selectHatchetMerchantList(hatchetMerchant);
		for (HatchetMerchant hatchetMerchant2 : list) {
		/*	if (hatchetMerchant2.getAgentId() != null) {
				HatchetAgent hatchetAgent = agentService.selectHatchetAgentById(hatchetMerchant2.getAgentId());
				if (hatchetAgent != null) {
					hatchetMerchant2.setAgentName(hatchetAgent.getAgentName());
					hatchetMerchant2.setAgentNo(hatchetAgent.getAgentNo());
				}
			}
			if (StringUtils.isNotEmpty(hatchetMerchant2.getBankCode())) {
				// 匹配银行名称
				HatchetIssBank issBankByBank = issBankService
						.selectHatchetIssBankByBankCode(hatchetMerchant2.getBankCode());
				if (StringUtils.isNotNull(issBankByBank)) {
					hatchetMerchant2.setBankName(issBankByBank.getBankName());
				}
			}
			if (hatchetMerchant2.getParentPhone() != null) {
				HatchetMerchant newMerchant = new HatchetMerchant();
				newMerchant.setPHONE(hatchetMerchant2.getParentPhone());
				List<HatchetMerchant> merlist = hatchetMerchantService.selectHatchetMerchantList(newMerchant);
				if (merlist.size() > 0) {
					hatchetMerchant2.setParentName(merlist.get(0).getMerchantCnName());
				}
			}*/
			//查询用户活跃度 查询用户的最近的一次的订单
			HatchetOrderPayment orderPayment = new HatchetOrderPayment();
			orderPayment.setMerchantId(hatchetMerchant2.getID());
			orderPayment.setSTATUS("10B");
			List<HatchetOrderPayment> orderPaymentList = orderPaymentService.selectHatchetOrderPaymentList(orderPayment);
			if (StringUtils.isNotEmpty(orderPaymentList)) {
				Date completeTime = orderPaymentList.get(0).getCompleteTime();
				if (StringUtils.isNotNull(completeTime)) {
					String liveness = DateUtils.formetaDiff(completeTime);
					hatchetMerchant2.setLiveness(liveness);
				}
			}else {                                                                                   
				hatchetMerchant2.setLiveness("不活跃");
			}
			//查询用户消费总金额
			BigDecimal selectSumMoney = orderPaymentService.selectSumMoney(orderPayment);
			hatchetMerchant2.setCreditRate(selectSumMoney);
		}
		ExcelUtil<HatchetMerchant> util = new ExcelUtil<HatchetMerchant>(HatchetMerchant.class);
		return util.exportExcel(list, "hatchetMerchant");
	}

	/**
	 * 修改商户列
	 */
	@GetMapping("/edit/{iD}")
	public String edit(@PathVariable("iD") String iD, ModelMap mmap) {
		HatchetMerchant hatchetMerchant = hatchetMerchantService.selectHatchetMerchantById(iD);
		if (hatchetMerchant.getAgentId() != null) {
			HatchetAgent agent = agentService.selectHatchetAgentById(hatchetMerchant.getAgentId());
			hatchetMerchant.setAgentName(agent.getAgentName());
			hatchetMerchant.setAgentNo(agent.getAgentNo());
		}
		mmap.put("hatchetMerchant", hatchetMerchant);
		return prefix + "/edit";
	}
	
	/**
	 * 跳转修改经理人页面
	 */
	@GetMapping("/editJLR/{iD}")
	public String editJLR(@PathVariable("iD") String iD, ModelMap mmap) {
		HatchetMerchant hatchetMerchant = hatchetMerchantService.selectHatchetMerchantById(iD);
		if (hatchetMerchant.getAgentId() != null) {
			HatchetAgent agent = agentService.selectHatchetAgentById(hatchetMerchant.getAgentId());
			hatchetMerchant.setAgentName(agent.getAgentName());
			hatchetMerchant.setAgentNo(agent.getAgentNo());
			//封装用户总分润
			hatchetMerchant.setSumMoney(moneyChangeService.selectSumFenRenChangeByUserId(hatchetMerchant.getMerchantNo()));
		}
		mmap.put("hatchetMerchant", hatchetMerchant);
		return prefix + "/editJLR";
	}

	
	/**
	 * 修改保存商户列
	 */
	@RequiresPermissions("system:hatchetMerchant:edit")
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(HatchetMerchant hatchetMerchant) {
		Map<String, Object> map = hatchetMerchantService.editSave(hatchetMerchant);
		if (BusinessStatus.SUCCESS.equals(map.get("status"))) {
			//调接口刷新用户在缓存的信息
			String params = "uid="+hatchetMerchant.getID()+"&sign="+StringUtils.getSign();
			String result = HttpUtils.sendGet(Constans.REFRESH_MER_URL, params);
			if (StringUtils.isEmpty(result)) {
				return AjaxResult.error("刷新用户信息到缓存失败");
			}
			JSONObject fromObject = JSONObject.fromObject(result);
			if ("0".equals(fromObject.getString("apistatus"))) {
				return AjaxResult.error("刷新用户信息到缓存失败");
			}
			return toAjax(1);
		}else {
			return AjaxResult.error((String)map.get("msg"));
		}
		
	}

	/**
	 * 
	 * @param hatchetMerchant
	 *            商户
	 * @param agentId
	 *            代理商
	 * @return
	 */
	@RequiresPermissions("system:hatchetMerchant:list")
	@PostMapping("/list/{agentId}")
	@ResponseBody
	public TableDataInfo list(HatchetMerchant hatchetMerchant, @PathVariable("agentId") String agentId) {
		hatchetMerchant.setAgentId(agentId);
		startPage();
		List<HatchetMerchant> list = hatchetMerchantService.selectHatchetMerchantList(hatchetMerchant);
		for (HatchetMerchant hatchetMerchant2 : list) {
			if (hatchetMerchant2.getAgentId() != null) {
				HatchetAgent hatchetAgent = agentService.selectHatchetAgentById(hatchetMerchant2.getAgentId());
				hatchetMerchant2.setAgentName(hatchetAgent.getAgentName());
				hatchetMerchant2.setAgentNo(hatchetAgent.getAgentNo());
			}
			if (hatchetMerchant2.getParentPhone() != null) {
				HatchetMerchant newMerchant = new HatchetMerchant();
				newMerchant.setPHONE(hatchetMerchant2.getParentPhone());
				List<HatchetMerchant> merlist = hatchetMerchantService.selectHatchetMerchantList(newMerchant);
				if (merlist.size() > 0) {
					hatchetMerchant2.setParentName(merlist.get(0).getMerchantCnName());
				}
			}
		}
		return getDataTable(list);
	}

	/**
	 * 修改客户状态--禁用/开启
	 */
	@RequiresPermissions("system:hatchetMerchant:edit")
	@PostMapping("/changeStatus")
	@ResponseBody
	public AjaxResult changeStatus(@PathParam("merchantId") String merchantId) {
		try {
			HatchetMerchant merchant = hatchetMerchantService.selectHatchetMerchantById(merchantId);
			if ("10A".equals(merchant.getUseStatus())) {
				merchant.setUseStatus("10B");
				hatchetMerchantService.updateHatchetMerchant(merchant);
				return AjaxResult.success("禁用成功");
			}
			if ("10B".equals(merchant.getUseStatus())) {
				merchant.setUseStatus("10A");
				hatchetMerchantService.updateHatchetMerchant(merchant);
				return AjaxResult.success("开启成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResult.error("操作失败，请联系管理员！");
		}
		return null;
	}
	
	
	
	/**
	 * 查询经理人申请列表
	 * @param hatchetMerchant 商户
	 * @return
	 */
	@RequiresPermissions("system:hatchetMerchant:list")
	@PostMapping("/selectJLR")
	@ResponseBody
	public TableDataInfo selectJLR(HatchetMerchant merchant) {
		/*//查询经纪人的升级经理人订单
		orderPayment.setTradeType("SJJLR");
		startPage();
		List<HatchetOrderPayment> orderPaymentList = orderPaymentService.selectHatchetOrderPaymentList(orderPayment);
		for (HatchetOrderPayment hatchetOrderPayment : orderPaymentList) {
			//匹配用户信息
			if (hatchetOrderPayment.getMerchantId() != null) {
				HatchetMerchant hatchetMerchant = hatchetMerchantService.selectHatchetMerchantById(hatchetOrderPayment.getMerchantId());
				if (hatchetMerchant !=null) {
					hatchetOrderPayment.setMerchantNo(hatchetMerchant.getMerchantNo());
					hatchetOrderPayment.setMerchantName(hatchetMerchant.getMerchantCnName());
					//借用time字段显示升级经理人状态
					hatchetOrderPayment.setTime(hatchetMerchant.getIsValid());
				}
			}
			if (hatchetOrderPayment.getAgentId() != null) {
				HatchetAgent agent = agentService.selectHatchetAgentById(hatchetOrderPayment.getAgentId());
				if (agent != null) {
					hatchetOrderPayment.setAgentNo(agent.getAgentNo());
					hatchetOrderPayment.setAgentName(agent.getAgentName());
				}
			}
		}
		return getDataTable(orderPaymentList);*/
		//查询用户表
		startPage();
		List<HatchetMerchant> list = hatchetMerchantService.selectJLR(merchant);
		for (HatchetMerchant hatchetMerchant2 : list) {
			if (hatchetMerchant2.getAgentId() != null) {
				HatchetAgent hatchetAgent = agentService.selectHatchetAgentById(hatchetMerchant2.getAgentId());
				if (hatchetAgent != null) {
					hatchetMerchant2.setAgentName(hatchetAgent.getAgentName());
					hatchetMerchant2.setAgentNo(hatchetAgent.getAgentNo());
				}
			}
			if (StringUtils.isNotEmpty(hatchetMerchant2.getBankCode())) {
				// 匹配银行名称
				HatchetIssBank issBankByBank = issBankService
						.selectHatchetIssBankByBankCode(hatchetMerchant2.getBankCode());
				if (StringUtils.isNotNull(issBankByBank)) {
					hatchetMerchant2.setBankName(issBankByBank.getBankName());
				}
			}
			if (hatchetMerchant2.getParentPhone() != null) {
				HatchetMerchant newMerchant = new HatchetMerchant();
				newMerchant.setPHONE(hatchetMerchant2.getParentPhone());
				List<HatchetMerchant> merlist = hatchetMerchantService.selectHatchetMerchantList(newMerchant);
				if (merlist.size() > 0) {
					hatchetMerchant2.setParentName(merlist.get(0).getMerchantCnName());
				}
			}
			//查询用户活跃度 查询用户的最近的一次的订单
			HatchetOrderPayment orderPayment = new HatchetOrderPayment();
			orderPayment.setMerchantId(hatchetMerchant2.getID());
			orderPayment.setSTATUS("10B");
			List<HatchetOrderPayment> orderPaymentList = orderPaymentService.selectHatchetOrderPaymentList(orderPayment);
			if (StringUtils.isNotEmpty(orderPaymentList)) {
				Date completeTime = orderPaymentList.get(0).getCompleteTime();
				if (StringUtils.isNotNull(completeTime)) {
					String liveness = DateUtils.formetaDiff(completeTime);
					hatchetMerchant2.setLiveness(liveness);
				}
				
			}else {
				hatchetMerchant2.setLiveness("不活跃");
			}
		}
		return getDataTable(list);
	}
	
	/**
	 * 审核经理人申请通过
	 */
	@RequiresPermissions("system:hatchetMerchant:edit")
	@PostMapping("/checkSuccess")
	@ResponseBody
	public Map<String,Object> checkSuccess(HatchetMerchant hatchetMerchant) {
		
		Map<String,Object> map = hatchetMerchantService.checkSuccess(hatchetMerchant,getLoginName());
		return map;
	}
	
	/**
	 * 审核经理人申请失败
	 */
	@RequiresPermissions("system:hatchetMerchant:edit")
	@PostMapping("/checkFail")
	@ResponseBody
	public Map<String,Object> checkFail(HatchetMerchant hatchetMerchant) {
		Map<String,Object> map = hatchetMerchantService.checkFail(hatchetMerchant,getLoginName());
		return map;
	}
	
	/**
	 * 对账销账
	 */
	/*@Log(title = "分润下发", businessType = BusinessType.DELETE)*/
	@PostMapping("/checkMoney")
	@ResponseBody
	@Transactional
	public Map<String, Object> checkMoney(String id) {
		Map<String, Object> requestmap = new HashMap<String, Object>();
		HatchetMerchant merchant = hatchetMerchantService.selectHatchetMerchantById(id);
		if (merchant!= null) {
			//总分润
			BigDecimal sumFenrun = moneyChangeService.selectSumFenRenChangeByUserId(merchant.getMerchantNo());
			HatchetMoneyChange moneyChange1 = new HatchetMoneyChange();
			//提现中
			moneyChange1.setUserId(merchant.getMerchantNo());
			moneyChange1.setSTATUS("10B");
			BigDecimal tixian1 = moneyChangeService.selectTixianSumMoney(moneyChange1);
			if (tixian1 == null) {
				tixian1 = new BigDecimal("0");
			}
			//提现通过
			moneyChange1.setUserId(merchant.getMerchantNo());
			moneyChange1.setSTATUS("10C");
			BigDecimal tixian2 = moneyChangeService.selectTixianSumMoney(moneyChange1);
			if (tixian2 == null) {
				tixian2 = new BigDecimal("0");
			}
			
			BigDecimal ktMoney = sumFenrun.subtract(tixian1).subtract(tixian2);
			//修改用户余额
			merchant.setTotalMoney(ktMoney);
			merchant.setUpdateTime(new Date());
			int a =  hatchetMerchantService.updateHatchetMerchant(merchant);
			if (a>0) {
				requestmap.put("status", "SUCCESS");
				requestmap.put("msg", "对账完成，请前往提现列表，重新审核");
				return requestmap;
			}else {
				requestmap.put("status", "FAIL");
				requestmap.put("msg", "对账失败，请联系技术！");
				return requestmap;
			}
		} else {
			requestmap.put("status", "FAIL");
			requestmap.put("msg", "商户账号异常，请联系技术");
			return requestmap;
		}
	}

	
}
